package org.darkforest.controller;

import java.util.*;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.darkforest.auth.AuthPassport;
import org.darkforest.auth.CurrentMember;
import org.darkforest.common.services.HealthUserService;
import org.darkforest.common.util.CalculateUserAgeUtils;
import org.darkforest.common.util.DateUtil;
import org.darkforest.dao.mapper.HealthCycleMapper;
import org.darkforest.dao.mapper.HealthDeptMapper;
import org.darkforest.dao.mapper.HealthOrgAppointmentMapper;
import org.darkforest.dao.mapper.HealthOrgMapper;
import org.darkforest.dao.mapper.HealthPackageMapper;
import org.darkforest.dao.mapper.HealthUserAppointmentMapper;
import org.darkforest.dao.mapper.HealthUserMapper;
import org.darkforest.dao.mapper.MemberMapper;
import org.darkforest.model.*;
import org.darkforest.vo.AjaxReturnData;
import org.darkforest.vo.HealthUserAppointVo;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping(value = "healthCheck")
@Api(value = "healthCheck", description = "体检管理",produces= MediaType.APPLICATION_JSON_VALUE)
public class HealthCheckController {

    org.slf4j.Logger logger = LoggerFactory.getLogger(HealthCheckController.class);

    @Autowired
    private HealthCycleMapper healthCycleMapper;
    @Autowired
    private HealthDeptMapper healthDeptMapper;
    @Autowired
    private HealthOrgMapper healthOrgMapper;
    @Autowired
    private HealthPackageMapper healthPackageMapper;
    @Autowired
    private HealthUserAppointmentMapper userAppointmentMapper;
    @Autowired
    private HealthOrgAppointmentMapper appointmentMapper;
    @Autowired
    private HealthUserMapper healthUserMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private HealthUserService healthUserService;


    @RequestMapping(value = "activeCycleList",method = RequestMethod.GET)
    @ApiOperation(value = "预约周期信息的取得", httpMethod = "GET",produces= MediaType.APPLICATION_JSON_VALUE)
    public RestEntity activeCycleList() {

        try{
            HealthCycle healthCycle = new HealthCycle();
            healthCycle.setPageSwitch(false);
            healthCycle.setCycleState("1");

            List<HealthCycle> healthCycleList = healthCycleMapper.selectListByCondition(healthCycle);

            // 当前系统时间（页面判断使用）
            //String serverDateStr = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
            if (healthCycleList != null && healthCycleList.size() > 0) {
                for (HealthCycle healthCycleDB : healthCycleList) {
                    healthCycleDB.setServerDate(DateUtil.unixTimeStampInt().intValue());
                }
            }

            return RestEntity.success(healthCycleList);
        } catch (Exception e){
            e.printStackTrace();
            return RestEntity.failed();
        }
    }

    @RequestMapping(value = "physicalExaminationCarDateList",method = RequestMethod.GET)
    @ApiOperation(value = "福临门大厦上门体检的预约日期", httpMethod = "GET",produces= MediaType.APPLICATION_JSON_VALUE)
    public RestEntity physicalExaminationCarDateList() {
        // 获取体检机构id
        HealthOrg healthOrg = new HealthOrg();
        healthOrg.setPageSwitch(false);
        healthOrg.setOrgName("福临门大厦上门体检");
        List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
        if (healthOrgList.size() != 1 || healthOrgList.get(0) == null) {
            return RestEntity.failed("体检机构数据异常");
        }
        final Integer orgId = healthOrgList.get(0).getOrgId();

        // 获取体检机构的有预约名额的日期
        List<String> appointmentDateList = new ArrayList<String>();
        HealthOrgAppointment hoAppointment = new HealthOrgAppointment();
        hoAppointment.setOrgId(orgId);
        List<HealthOrgAppointment> hoaInfoList = appointmentMapper.selectListByCondition(hoAppointment);
        String today = DateUtil.toIntDateString(DateUtil.unixTimeStampInt().intValue(), DateUtil.DEFAULT_DATE_PATTERN);
        for (HealthOrgAppointment healthOrgAppointment : hoaInfoList) {
            String appointmentDate = DateUtil.toIntDateString(healthOrgAppointment.getAppointmentDate(), DateUtil.DEFAULT_DATE_PATTERN);
            if (today.compareTo(appointmentDate) <= 0 && healthOrgAppointment.getAppointmenterNum() > 0) {
                appointmentDateList.add(appointmentDate);
            }
        }

        Collections.sort(appointmentDateList);
        return RestEntity.success(appointmentDateList);
    }

    /**
     *  页面月份变化时调用
     *
     * @param yearMonth
     * @return
     */
    @RequestMapping(value = "monthAppointList",method = RequestMethod.GET)
    @ApiOperation(value = "每个月所有机构的预约信息", httpMethod = "GET",produces= MediaType.APPLICATION_JSON_VALUE)
    public RestEntity monthAppointList(@RequestParam(required = true) String  yearMonth) {

        try{
            // 取得指定月份的已设定预约信息的机构
            Map<String, String> searchMap = new HashMap<String, String>();
            //  %Y%m  yyyyMM 格式
            searchMap.put("yearMonth", yearMonth);

            List<HealthOrgCheckedAppointment> appointmentList = appointmentMapper.selectEveryDayInfoByMonth(searchMap);

            return RestEntity.success(appointmentList);
        } catch (Exception e){
            e.printStackTrace();
            return RestEntity.failed();
        }
    }

    @AuthPassport
    @RequestMapping(value = "userAppointList",method = RequestMethod.GET)
    @ApiOperation(value = "当前用户的所有预约信息", httpMethod = "GET",produces= MediaType.APPLICATION_JSON_VALUE)
    public RestEntity userAppointList(@CurrentMember Member member) {

        try{

            HealthUserAppointVo healthUserAppointVo = new HealthUserAppointVo();

            // 当前登录者手机号的取得
            MemberWithBLOBs memberInfo = memberMapper.selectByPrimaryKey(member.getMemberId());
            memberInfo.setPageSwitch(false);
            String memberMobile = memberInfo.getMemberMobile();

            // 当前登录者预约信息的取得
            // 根据手机号取得该用户的所有预约信息（所有年份的，所有体检状态）
            HealthUser healthUser = new HealthUser();
            healthUser.setMobPhone(memberMobile);
            healthUser.setPageSwitch(false);
            List<HealthUser> userList = healthUserMapper.selectListByCondition(healthUser);

            // 根据手机号只会取得一个用户
            if ((userList != null) && (userList.size() > 0)) {
                healthUser = userList.get(0);

                // 当前用户基本信息的设定（页面用户有没有导入的判断，与有没有预约没有关系）
                // 根据用户deptId，取得deptName
                HealthDept healthDept = healthDeptMapper.selectByPrimaryKey(healthUser.getDeptId());
                healthUser.setDeptName(healthDept.getDeptName());
                // 设置当前用户信息
                healthUserAppointVo.setHealthUser(healthUser);


                // 设置体检机构
                HealthOrg healthOrg = new HealthOrg();
                healthOrg.setPageSwitch(false);
                healthOrg.setOrgState(true);
                List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
                // 根据用户所属的业务单元，过滤体检机构选项
                if(!StringUtils.isBlank(healthDept.getOrgIds())) {
                    List<HealthOrg> retHealthOrgList = new ArrayList<HealthOrg>();
                    String[] orgIdArray = healthDept.getOrgIds().split(",");
                    // 取得该业务单元设定的的体检机构
                    if (healthOrgList != null && healthOrgList.size() > 0) {
                        for (HealthOrg healthOrg1: healthOrgList) {
                            for (String orgId: orgIdArray) {
                                if (healthOrg1.getOrgId().intValue() == Integer.valueOf(orgId).intValue()) {
                                    retHealthOrgList.add(healthOrg1);
                                    break;
                                }
                            }
                        }
                    }
                    healthDept.setOrgList(retHealthOrgList);
                } else {
                    healthDept.setOrgList(healthOrgList);
                }
                // 根据用户的套餐类型、业务单元，过滤体检机构选项
                String pkgType = healthUser.getPkgType();
                List<HealthOrg> retretHealthOrgList = new ArrayList<HealthOrg>();
                if (!StringUtils.isBlank(pkgType)) {
                    List<HealthOrg> initOrgList = healthDept.getOrgList();
                    //B1、B2套餐类型的体检机构是: 北京电力医院(含无痛胃肠镜)、北京电力医院(不含无痛胃肠镜)、北京航天中心医院(含无痛胃肠镜)、北京航天中心医院(不含无痛胃肠镜)、福临门大厦上门体检
                    //C1、C2、C3、C4套餐类型、并且2023年已做或已保留无痛胃肠镜项目的体检机构是: 美兆东方广场分院、美兆润美分院、爱康双子座君安分院、爱康大望路分院、爱康光华路SOHO分院、北京电力医院(不含无痛胃肠镜)、北京航天中心医院(不含无痛胃肠镜)、福临门大厦上门体检
                    //C1、C2、C3、C4套餐类型、并且2023年未做或未保留无痛胃肠镜项目、但后续安排无痛胃肠镜的体检机构是: 美兆东方广场分院、美兆润美分院、北京电力医院(含无痛胃肠镜)、北京航天中心医院(含无痛胃肠镜)、福临门大厦上门体检
                    //C1、C2、C3、C4套餐类型、并且2023年未做或未保留无痛胃肠镜项目、后续不安排无痛胃肠镜的体检机构是: 美兆东方广场分院、美兆润美分院、爱康双子座君安分院、爱康大望路分院、爱康光华路SOHO分院、北京电力医院(不含无痛胃肠镜)、北京航天中心医院(不含无痛胃肠镜)、福临门大厦上门体检
                    //D1、D2、D3、D4套餐类型、并且后续安排无痛胃肠镜的体检机构是: 北京电力医院D、北京航天中心医院(西三环)、福临门大厦上门体检、北京航天中心医院(玉泉路D)
                    //D1、D2、D3、D4套餐类型、并且后续不安排无痛胃肠镜的体检机构是: 美兆东方广场分院、美兆润美分院、爱康双子座君安分院、爱康大望路分院、爱康光华路SOHO分院、北京中医医院、北京电力医院D、北京航天中心医院(西三环)、福临门大厦上门体检、北京航天中心医院(玉泉路D)
                    if (pkgType.equals("B1") || pkgType.equals("B2")) {
                        for (HealthOrg healthOrg1 : initOrgList) {
                            for (String healthOrgName : Arrays.asList("北京电力医院(含无痛胃肠镜)", "北京电力医院(不含无痛胃肠镜)", "北京航天中心医院(含无痛胃肠镜)", "北京航天中心医院(不含无痛胃肠镜)", "福临门大厦上门体检")) {
                                if (healthOrg1.getOrgName().equals(healthOrgName)) {
                                    retretHealthOrgList.add(healthOrg1);
                                    break;
                                }
                            }
                        }
                    } else if (pkgType.equals("C1") || pkgType.equals("C2") || pkgType.equals("C3") || pkgType.equals("C4")) {
                        List<String> orgNameList = Arrays.asList("美兆东方广场分院", "美兆润美分院", "爱康双子座君安分院", "爱康大望路分院", "爱康光华路SOHO分院", "北京电力医院(含无痛胃肠镜)", "北京电力医院(不含无痛胃肠镜)", "北京航天中心医院(含无痛胃肠镜)", "北京航天中心医院(不含无痛胃肠镜)", "福临门大厦上门体检");
                        for (HealthOrg healthOrg1 : initOrgList) {
                            for (String healthOrgName : orgNameList) {
                                if (healthOrg1.getOrgName().equals(healthOrgName)) {
                                    retretHealthOrgList.add(healthOrg1);
                                    break;
                                }
                            }
                        }
                    } else if (pkgType.equals("D1") || pkgType.equals("D2") || pkgType.equals("D3") || pkgType.equals("D4")) {
                        List<String> list = Arrays.asList("美兆东方广场分院", "美兆润美分院", "爱康双子座君安分院", "爱康大望路分院", "爱康光华路SOHO分院", "北京中医医院", "北京电力医院D", "北京航天中心医院(西三环)", "福临门大厦上门体检", "北京航天中心医院(玉泉路D)");
                        for (HealthOrg healthOrg1 : initOrgList) {
                            for (String healthOrgName : list) {
                                if (healthOrg1.getOrgName().equals(healthOrgName)) {
                                    retretHealthOrgList.add(healthOrg1);
                                    break;
                                }
                            }
                        }
                    }
                    healthDept.setOrgList(retretHealthOrgList);
                }
                healthUserAppointVo.setHealthDept(healthDept);

                // 根据用户的套餐类型、体检机构，设置胸部CT、必选项、自选项
                for (HealthOrg healthOrg1 : healthDept.getOrgList()) {
                    List<String> breastCTList = new ArrayList<String>();
                    List<String> requiredOptionList = new ArrayList<String>();
                    String orgName = healthOrg1.getOrgName();

                    if (orgName.equals("美兆东方广场分院")) {
                        if (pkgType.equals("C1") || pkgType.equals("C2") || pkgType.equals("C3") || pkgType.equals("C4")) {
                            // 无必选项
                        }

                        // 设置胸部CT的选择
                        if (pkgType.equals("D1") || pkgType.equals("D2") || pkgType.equals("D3") || pkgType.equals("D4")) {
                            breastCTList.add("有胸部CT");
                        }
                    } else if (orgName.equals("美兆润美分院")) {
                        if (pkgType.equals("C1") || pkgType.equals("C2") || pkgType.equals("C3") || pkgType.equals("C4")) {
                            // 无必选项
                        }

                        // 设置胸部CT的选择
                        if (pkgType.equals("D1") || pkgType.equals("D2") || pkgType.equals("D3") || pkgType.equals("D4")) {
                            breastCTList.add("有胸部CT");
                        }
                    } else if (orgName.equals("爱康双子座君安分院") || orgName.equals("爱康大望路分院") || orgName.equals("爱康光华路SOHO分院")) {
                        if (pkgType.equals("C1") || pkgType.equals("C2") || pkgType.equals("C3") || pkgType.equals("C4")) {
                            requiredOptionList.add("①头部核磁+胸部CT+颈椎X光");
                            requiredOptionList.add("②头部核磁+胸部CT+腰椎X光");
                            requiredOptionList.add("③胸部核磁+头部CT+颈椎X光");
                            requiredOptionList.add("④胸部核磁+头部CT+腰椎X光");
                            requiredOptionList.add("⑤无核磁");
                        }

                        if (pkgType.equals("D1") || pkgType.equals("D2") || pkgType.equals("D3") || pkgType.equals("D4")) {
                            breastCTList.add("有胸部CT");
                        }
                    } else if (orgName.equals("北京电力医院(含无痛胃肠镜)")) {
                        if (pkgType.equals("B1") || pkgType.equals("B2")) {
                            requiredOptionList.add("①心脑血管风险筛查");
                            requiredOptionList.add("②关节痛检测");
                            requiredOptionList.add("③复检、待检卡");
                        }

                        if (pkgType.equals("C1") || pkgType.equals("C2") || pkgType.equals("C3") || pkgType.equals("C4")) {
                            requiredOptionList.add("①心脏冠状动脉CT");
                            requiredOptionList.add("②亚健康及慢性病风险检测");
                            requiredOptionList.add("③关节痛检测");
                            requiredOptionList.add("④头部血管核磁造影");
                        }
                    } else if (orgName.equals("北京电力医院(不含无痛胃肠镜)")) {
                        if (pkgType.equals("B1") || pkgType.equals("B2")) {
                            requiredOptionList.add("①心脑血管风险筛查");
                            requiredOptionList.add("②关节痛检测");
                            requiredOptionList.add("③复检、待检卡");
                        }

                        if (pkgType.equals("C1") || pkgType.equals("C2") || pkgType.equals("C3") || pkgType.equals("C4")) {
                            requiredOptionList.add("①心脏冠状动脉CT");
                            requiredOptionList.add("②亚健康及慢性病风险检测");
                            requiredOptionList.add("③关节痛检测");
                            requiredOptionList.add("④头部血管核磁造影");
                        }
                    } else if (orgName.equals("北京电力医院D")) {
                        // 设置必选项
                        if (pkgType.equals("D1") || pkgType.equals("D2") || pkgType.equals("D3") || pkgType.equals("D4")) {
                            requiredOptionList.add("①心血管危险因素筛查");
                            requiredOptionList.add("②糖尿病风险筛查");
                        }
                    } else if (orgName.equals("北京航天中心医院(含无痛胃肠镜)")) {
                        if (pkgType.equals("B1") || pkgType.equals("B2")) {
                            requiredOptionList.add("①心脑血管风险筛查");
                            requiredOptionList.add("②关节痛检测");
                            requiredOptionList.add("③复检、待检卡");
                        }

                        if (pkgType.equals("C1") || pkgType.equals("C2") || pkgType.equals("C3") || pkgType.equals("C4")) {
                            requiredOptionList.add("①心脏冠状动脉CT");
                            requiredOptionList.add("②关节痛检测");
                            requiredOptionList.add("③头部血管核磁造影");
                        }
                    } else if (orgName.equals("北京航天中心医院(不含无痛胃肠镜)")) {
                        if (pkgType.equals("B1") || pkgType.equals("B2")) {
                            requiredOptionList.add("①心脑血管风险筛查");
                            requiredOptionList.add("②关节痛检测");
                            requiredOptionList.add("③复检、待检卡");
                        }

                        if (pkgType.equals("C1") || pkgType.equals("C2") || pkgType.equals("C3") || pkgType.equals("C4")) {
                            requiredOptionList.add("①心脏冠状动脉CT");
                            requiredOptionList.add("②关节痛检测");
                            requiredOptionList.add("③头部血管核磁造影");
                        }
                    } else if (orgName.equals("北京航天中心医院(西三环)") || orgName.equals("北京航天中心医院(玉泉路D)")) {
                        // 设置必选项
                        if (pkgType.equals("D1") || pkgType.equals("D2") || pkgType.equals("D3") || pkgType.equals("D4")) {
                            requiredOptionList.add("①心血管危险因素筛查");
                            requiredOptionList.add("②胃功能筛查");
                            requiredOptionList.add("③心脏彩超检查");
                        }
                    } else if (orgName.equals("福临门大厦上门体检")) {
                        // 无必选项
                    }

                    healthOrg1.setBreastCTList(breastCTList);
                    healthOrg1.setRequiredOptionList(requiredOptionList);
                }

                // 状态 1:未预约 2:已预约 3:已取消 4:已体检 5:体检完成
                if ("1".equals(healthUser.getState()) ||  "3".equals(healthUser.getState())) {
                    // 不设定（实际应根据userAppointmentMapper的State 判断）
                } else {
                    // 根据用户ID，取得当前用的所有预约信息
                    HealthUserAppointment userAppointment = new HealthUserAppointment();
                    userAppointment.setUserId(healthUser.getUserId());
                    userAppointment.setAppointmentedFlg("1");       // 已预约的
                    userAppointment.setPageSwitch(false);
                    List<HealthUserAppointment>  userAppointmentList = userAppointmentMapper.selectListByCondition(userAppointment);

                    healthUserAppointVo.setUserAppointmentList(userAppointmentList);
                }
            }

            return RestEntity.success(healthUserAppointVo);
        } catch (Exception e){
            e.printStackTrace();
            return RestEntity.failed();
        }
    }

    @RequestMapping(value = "userAppointment", method = RequestMethod.POST)
    @ApiOperation(value = "用户预约", httpMethod = "POST",produces= MediaType.APPLICATION_JSON_VALUE)
    public RestEntity userAppointment(@RequestBody HealthUser healthUserRecord, @RequestParam(required = true) String  appointmentFlg) {
        try{

            // String memberMobile, String checkDate, Integer orgId
            AjaxReturnData ajaxReturnData = null;

            // 预约、重新预约
            if ("1".equals(appointmentFlg)) {
                // 判断套餐类型是否会因为在体检日期当天用户的年龄达到了40岁而发生变化
                if (healthUserRecord.getUserAge() == 39 && StringUtils.isNotBlank(healthUserRecord.getCheckDateStr())) {
                    if (healthUserRecord.getPkgType().startsWith("C") || healthUserRecord.getPkgType().startsWith("D")) {
                        // 计算体检日期当天，用户的年龄
                        Date checkDate = DateUtil.strToDate(healthUserRecord.getCheckDateStr(), DateUtil.DEFAULT_DATE_PATTERN);
                        int age = CalculateUserAgeUtils.calculate(healthUserRecord.getCardId(), checkDate);
                        if (age == 40) {
                            return RestEntity.failed("发现预约日期跨越40岁 提前预约日期会产生套餐变更 请联系管理员");
                        }
                    }
                }

                // String memberMobile, String checkDate, Integer orgId
                ajaxReturnData =  healthUserService.appointmentCheckup(healthUserRecord);
            } else {
                // 取消预约
                ajaxReturnData =  healthUserService.cancelCheckup(healthUserRecord.getMobPhone(), healthUserRecord.getCheckDateStr());
            }

            // 预约成功、取消成功
            if (ajaxReturnData.isResult()) {
                return RestEntity.success(ajaxReturnData);
            } else {
                // 预约有错误时
                return RestEntity.failed(ajaxReturnData.getMessage());
            }
        }catch (Exception e){
            e.printStackTrace();
            return RestEntity.failed();
        }
    }
}
